package com.mlnx.work.service.iml;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mlnx.work.dao.mysql.RightMapper;
import com.mlnx.work.entity.Right;
import com.mlnx.work.pojo.form.RightForm;
import com.mlnx.work.pojo.vo.RightVo;
import com.mlnx.work.service.RightService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;

/**
 * author name: amanda.shan
 * create time: 2020-12-28 17:09:55
 */
@Service
public class RightServiceIml extends BaseService<RightMapper, Right> implements RightService {

    @Autowired
    @Override
    public void setBaseMapper(RightMapper baseMapper) {
        super.setBaseMapper(baseMapper);
    }


    @Override
    public List<Right> getParentRights() {
        return null;
    }

    @Override
    public List<RightVo> getAll() {

        List<Right> rights = list(new QueryWrapper<>());

        Map<Integer, RightVo> rightVos = new HashMap<>();
        List<Right> tempRights = new ArrayList<>();

        while (rights.size() > 0) {
            for (Right right : rights) {

                if (right.getParentId() == 0) {
                    RightVo rightVo = getRightVo(right);
                    rightVos.put(rightVo.getId(), rightVo);
                    continue;
                }

                RightVo parentRightVo = rightVos.get(right.getParentId());
                if (parentRightVo != null) {
                    RightVo rightVo = getRightVo(right);
                    parentRightVo.getRightVos().add(rightVo);
                    rightVos.put(right.getId(), rightVo);
                } else {
                    tempRights.add(right);
                }
            }

            if (rights.size() == tempRights.size()) {
                log.error("有些权限不存在任何父权限:{}", tempRights);
                break;
            }

            rights.clear();
            rights.addAll(tempRights);
            tempRights.clear();
        }


        List<RightVo> rightVos1 = new ArrayList<>();
        for (RightVo rightVo : rightVos.values()) {
            if (rightVo.getParentId() == 0) {
                rightVos1.add(rightVo);
            }
        }

        return rightVos1;
    }

    @Override
    public void add(RightForm rightForm) {

        Right right = new Right();
        BeanUtil.copyProperties(rightForm, right);
        save(right);
    }

    @Override
    public List<Right> getRightsByUserName(String username) {

        return baseMapper.slectRightsByUsername(username);
    }

    private RightVo getRightVo(Right right) {

        RightVo rightVo = new RightVo();
        BeanUtil.copyProperties(right, rightVo);
        rightVo.setId(right.getId());

        return rightVo;
    }
}

